package com.kuaimacode.kframework.admin.controller.agent;

import com.github.pagehelper.PageInfo;
import com.kuaimacode.kframework.admin.services.agent.SysAgentService;
import com.kuaimacode.kframework.admin.services.sys.SysAreaService;
import com.kuaimacode.kframework.admin.services.user.SysAdminUserService;
import com.kuaimacode.kframework.admin.vo.request.AgentOrderReq;
import com.kuaimacode.kframework.admin.vo.response.AgentOrderResp;
import com.kuaimacode.kframework.common.JsonResult;
import com.kuaimacode.kframework.constants.PageConstants;
import com.kuaimacode.kframework.exception.ErrorEnum;
import com.kuaimacode.kframework.exception.ServerInternalErrorException;
import com.kuaimacode.kframework.mybatis.models.agent.SysAgent;
import com.kuaimacode.kframework.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;

/**
 * @author Administrator
 * @date 2019/03/31
 */

/**
 * Controller
 */
@Controller
@RequestMapping({"/agent"})
public class AgentController {
    private static String PAGE_FILE_NAME = "agent/";

    @Autowired
    private SysAgentService agentServices;
    @Autowired
    private SysAreaService areaService;
    @Autowired
    private SysAdminUserService adminUserService;

    @RequestMapping(value = {"/index"})
    public String index(@RequestParam(value = "pageNum", defaultValue = PageConstants.PAGE_NUM + "") int pageNum,
                        @RequestParam(value = "pageSize", defaultValue = PageConstants.PAGE_SIZE + "") int pageSize,
                        ModelMap model, SysAgent searchAgent) {
        PageInfo<SysAgent> pageInfo = agentServices.findAll(pageNum, pageSize, searchAgent);
        // pageInfo.list agent
        model.put("pageInfo", pageInfo);
        searchAgent.setStat(Optional.ofNullable(searchAgent.getStat()).orElse(0));
        model.put("searchAgent", searchAgent);
        model.put("endTime", DateUtil.getNow(DateUtil.LONG_DATE_FORMAT));
        model.put("startTime", DateUtil.format(DateUtil.plus(DateUtil.DateEnum.MONTH, -1), DateUtil.LONG_DATE_FORMAT));
        return PAGE_FILE_NAME + "index";
    }


    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String add(ModelMap map) {
        SysAgent agent = new SysAgent();
        map.put("areas", areaService.notAddList());
        map.put("agent", agent);
        map.put("isAdd", true);
        return PAGE_FILE_NAME + "form";
    }

    @RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
    public String edit(@PathVariable String id, ModelMap map) {
        SysAgent agent = agentServices.getById(id);
        map.put("agent", agent);
        map.put("isAdd", false);
        return PAGE_FILE_NAME + "form";
    }

    @RequestMapping(value = {"/edit"}, method = RequestMethod.POST)
    @ResponseBody
    public JsonResult edit(SysAgent agent, Boolean isAdd) {
        try {
            if (isAdd) {
                if (agentServices.hasAgent(agent.getId())) {
                    throw new ServerInternalErrorException(ErrorEnum.AGENT_ALREADY_EXISTS);
                }
                // 新建保存
                agentServices.save(agent);
            } else {
                // 编辑保存
                agentServices.updateAgent(agent);
            }
        } catch (Exception e) {
            return JsonResult.failure(e.getMessage());
        }
        return JsonResult.success();
    }


    @RequestMapping(value = "/detail/{id}", method = RequestMethod.GET)
    public String detail(@PathVariable String id, ModelMap map) {
        SysAgent agent = agentServices.getById(id);
        /*List<SysAdminUser> adminUsers = adminUserService.list();
        if (adminUsers != null) {
            adminUsers.stream().filter(adminUser -> adminUser.getUserId().equals(agent.getOpenBy()))
                    .findFirst().ifPresent(adminUser -> agent.setOpenName(adminUser.getUserName()));
        }*/
        map.put("agent", agent);
        return PAGE_FILE_NAME + "detail";
    }

    @ResponseBody
    public JsonResult delete(@PathVariable String id, ModelMap map) {
        try {
            agentServices.removeById(id);
        } catch (Exception e) {
            return JsonResult.failure(e.getMessage());
        }
        return JsonResult.success();
    }

    /**
     * 开通分站
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/openAgent/{id}", method = RequestMethod.GET)
    public String openAgent(@PathVariable String id, ModelMap map) {
        SysAgent agent = agentServices.getById(id);
        agent.setStat(0);
        map.put("agent", agent);
        map.put("isAdd", false);
        return PAGE_FILE_NAME + "form";
    }

    /**
     * 关闭分站
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/closeAgent/{id}", method = RequestMethod.GET)
    @ResponseBody
    public JsonResult closeAgent(@PathVariable String id) {
        return JsonResult.success(agentServices.closeAgent(id));
    }

    @ResponseBody
    @GetMapping(value = "/resetPassword/{id}")
    public JsonResult resetPassword(@PathVariable String id) {
        agentServices.resetPassword(id);
        return JsonResult.success();
    }

    @GetMapping("/agentOrder")
    public String agentOrder(@Valid AgentOrderReq req, ModelMap map,
                             @RequestParam(value = "pageNum", defaultValue = PageConstants.PAGE_NUM + "") int pageNum,
                             @RequestParam(value = "pageSize", defaultValue = PageConstants.PAGE_SIZE + "") int pageSize) {
        if (DateUtil.dayDiff(DateUtil.stringtoDate(req.getStartTime(), DateUtil.LONG_DATE_FORMAT), DateUtil.stringtoDate(req.getEndTime(), DateUtil.LONG_DATE_FORMAT)) > 31) {
            map.put("errorMsg", "相隔天数不能超过31天");
            map.put("agentOrderList", new ArrayList<>());
            map.put("collect", new HashMap<>());
        } else {
            List<AgentOrderResp> list = agentServices.findAgentOrderDetail(req, pageNum, pageSize);
            Optional.ofNullable(list).ifPresent(agentOrderResps -> agentOrderResps.forEach(AgentOrderResp::exchangeTranType));
            map.put("agentOrderList", list);
            map.put("collect", agentServices.findCollectInfo(req));
        }
        map.put("orderReq", req);
        return PAGE_FILE_NAME + "agent_order_list";
    }

    @GetMapping("/agentOrderInner")
    public String agentOrderInner(@Valid AgentOrderReq req, ModelMap map,
                             @RequestParam(value = "pageNum", defaultValue = PageConstants.PAGE_NUM + "") int pageNum,
                             @RequestParam(value = "pageSize", defaultValue = PageConstants.PAGE_SIZE + "") int pageSize) {
        if (DateUtil.dayDiff(DateUtil.stringtoDate(req.getStartTime(), DateUtil.LONG_DATE_FORMAT), DateUtil.stringtoDate(req.getEndTime(), DateUtil.LONG_DATE_FORMAT)) > 31) {
            map.put("errorMsg", "相隔天数不能超过31天");
            map.put("agentOrderList", new ArrayList<>());
            map.put("collect", new HashMap<>());
        } else {
            List<AgentOrderResp> list = agentServices.findAgentOrderDetail(req, pageNum, pageSize);
            Optional.ofNullable(list).ifPresent(agentOrderResps -> agentOrderResps.forEach(AgentOrderResp::exchangeTranType));
            map.put("agentOrderList", list);
            map.put("collect", agentServices.findCollectInfo(req));
        }
        map.put("orderReq", req);
        return PAGE_FILE_NAME + "agent_order_list_inner";
    }

    @GetMapping("/agentOrderExport")
    public void agentOrderExport(@Valid AgentOrderReq req,
                                   @RequestParam(value = "pageNum", defaultValue = PageConstants.PAGE_NUM + "") int pageNum,
                                   @RequestParam(value = "pageSize", defaultValue = PageConstants.PAGE_SIZE + "") int pageSize,
                                   HttpServletResponse response) {
        agentServices.agentOrderExport(req, pageNum, pageSize, response);
    }
}
